package flc.ast.activity;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UriUtils;
import com.stark.file.transfer.core.FileInfo;
import com.stark.file.transfer.core.TfContactInfo;
import com.stark.file.transfer.core.Transferable;
import com.stark.file.transfer.core.TransferableSendManager;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.bean.SelectFileBean;
import flc.ast.databinding.ActivityMutualTransferBinding;
import flc.ast.utils.Content;
import flc.ast.utils.FileUploader;
import flc.ast.utils.SendFileManager;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.bean.ContactInfo;
import stark.common.basic.constant.FileType;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.RxUtil;

public class MutualTransferActivity extends BaseAc<ActivityMutualTransferBinding> {


    @Override
    protected int onCreate() {
        return R.layout.activity_mutual_transfer;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent5(this, mDataBinding.event5Container);

        mDataBinding.ivMutualTransferBack.setOnClickListener(v -> getOnBackPressedDispatcher().onBackPressed());

        mDataBinding.ivUseInst.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.ivUseInst) {//使用说明
            startActivity(TransferInstActivity.class);
        }
    }

    @Override
    protected void initData() {
        List<File> selectedFiles = new ArrayList<>();
        for (SelectFileBean fileBean : SendFileManager.getInstance().getSelectFileBeans()) {
            selectedFiles.add(UriUtils.uri2File(Uri.parse(fileBean.getPath())));
        }
//        new FileUploader.MultiFileUploadTask().execute(getIp(), String.valueOf(Content.Port), selectedFiles);
//        new MultiFileUploadTask().execute(getIp(), String.valueOf(Content.Port), selectedFiles);
        uploadFile(getIp(), Content.Port, selectedFiles);
    }


    //上传文件
    private void uploadFile(String ip, int port, List<File> files) {
        int progress = new Random().nextInt(50) + 10;
        mDataBinding.sbProgress.setProgress(progress);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<String>() {

                    @Override
                    public void doBackground(ObservableEmitter<String> emitter) {
                        String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
                        String lineEnd = "\r\n";
                        String twoHyphens = "--";

                        try {
                            URL url = new URL("http://" + ip + ":" + port);
                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            conn.setDoInput(true);
                            conn.setDoOutput(true);
                            conn.setUseCaches(false);
                            conn.setRequestMethod("POST");
                            conn.setRequestProperty("Connection", "Keep-Alive");
                            conn.setRequestProperty("Charset", "UTF-8");
//                            conn.setRequestProperty("Cache-Control", "no-cache");
                            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                            // 遍历所有文件并写入请求体
                            for (File file : files) {
                                dos.writeBytes(twoHyphens + boundary + lineEnd);
                                dos.writeBytes("Content-Disposition: form-data; name=\"files\"; filename=\"" +
                                        file.getName() + "\"" + lineEnd);
                                dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
                                dos.writeBytes(lineEnd);

                                FileInputStream fis = new FileInputStream(file);
                                byte[] buffer = new byte[4096];
                                int bytesRead;
                                while ((bytesRead = fis.read(buffer)) != -1) {
                                    dos.write(buffer, 0, bytesRead);
                                }
                                fis.close();
                                dos.writeBytes(lineEnd);
                            }

                            // 结束标记
                            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                            dos.flush();
                            dos.close();

                            // 读取响应
                            int responseCode = conn.getResponseCode();
                            if (responseCode == HttpURLConnection.HTTP_OK) {
                                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                                StringBuilder response = new StringBuilder();
                                String inputLine;
                                while ((inputLine = in.readLine()) != null) {
                                    response.append(inputLine);
                                }
                                in.close();
                                emitter.onNext(getString(R.string.upload_suc));
                            } else {
                                emitter.onNext(getString(R.string.upload_error) + responseCode);
                            }
                        } catch (Exception e) {
                            emitter.onNext(getString(R.string.upload_exception) + e.getMessage());
                        }
                    }

                    @Override
                    public void accept(String result) {
                        mDataBinding.tvTitle.setText(result);
                        mDataBinding.sbProgress.setProgress(100);
                    }
                });
            }
        }, 1000);
    }

    private class MultiFileUploadTask extends AsyncTask<Object, Void, String> {

        @Override
        protected String doInBackground(Object... params) {
            String ip = (String) params[0];
            int port = Integer.parseInt((String) params[1]);
            List<File> files = (List<File>) params[2];

            String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
            String lineEnd = "\r\n";
            String twoHyphens = "--";

            try {
                URL url = new URL("http://" + ip + ":" + port);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setUseCaches(false);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Cache-Control", "no-cache");
                conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

                DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

                // 遍历所有文件并写入请求体
                for (File file : files) {
                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"files\"; filename=\"" +
                            file.getName() + "\"" + lineEnd);
                    dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
                    dos.writeBytes(lineEnd);

                    FileInputStream fis = new FileInputStream(file);
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = fis.read(buffer)) != -1) {
                        dos.write(buffer, 0, bytesRead);
                    }
                    fis.close();
                    dos.writeBytes(lineEnd);
                }

                // 结束标记
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                dos.flush();
                dos.close();

                // 读取响应
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder response = new StringBuilder();
                    String inputLine;
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    return getString(R.string.upload_suc);
                } else {
                    return getString(R.string.upload_error) + responseCode;
                }
            } catch (Exception e) {
                return getString(R.string.upload_exception) + e.getMessage();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            mDataBinding.tvTitle.setText(result);
            mDataBinding.sbProgress.setProgress(100);
        }

    }

    /**
     * 返回当前设备的ip地址
     *
     * @return
     */
    private String getIp() {
        String ip = NetworkUtils.getIPAddress(true);
        ;
        try {
            String wifiIp = NetworkUtils.getIpAddressByWifi();
            //这里添加这样的处理是因为发现有在小米的Android12系统的手机上通过NetworkUtils.getIPAddress无法
            //获取到局域网地址，而是直接获取到公网地址
            if (!TextUtils.isEmpty(wifiIp) && wifiIp.startsWith("192")) {
                return wifiIp;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }

}